#include "pthreadpool.h"

pthreadpool::pthreadpool()
{
    head = new struct thread;
	head->tid	= -1;
	head->number	= -1;
	head->status	= RUN;
	head->next	= NULL;
}

bool pthreadpool::_create_(int number)
{
	thread* buff	= head;
	while(buff->next != NULL){
		buff	= buff->next;
	}
	thread* temp	= new struct thread;
	buff->next	= temp;
	pthread_create(&temp->tid,NULL,&func,(void*)temp);
	temp->next	= NULL;
	temp->sock	= -1;
	temp->status	= STOP;
	temp->number	= number;
	pthread_mutex_init(&temp->mutex,NULL);
	pthread_cond_init(&temp->cond,NULL);
	return true;
}

bool pthreadpool::_wake_(int sock)
{
	thread* temp = head;
	while(temp->status != STOP){
		temp = temp->next;
		if(temp == NULL){
			cout<<"NO MORE STRUCT PTHREAD!"<<endl;
			return false;
		}
	}
	temp->sock   = sock;
	temp->status = RUN;
	pthread_cond_signal(&temp->cond);
	return true;
}

/*bool pthreadpool::_sleep_()
{
	pthread_t tid;
	thread* temp = head;
	while(temp->tid != tid){
		temp = temp->next;
	}
	temp->sock   = -1;
	temp->status = STOP;
	return true;
}*/

void* pthreadpool::func(void* s_thread)
{
	thread* temp = (thread*)s_thread;
	while(1){
		pthread_mutex_lock(&temp->mutex);
		if(temp->status == STOP){
			pthread_cond_wait(&temp->cond,&temp->mutex);
		}
		//while(1);
		cout<<temp->tid<<endl;
		temp->sock	= -1;
		temp->status	= STOP;
		pthread_mutex_unlock(&temp->mutex);
	}
}
